// routes/flights.ts
import express from 'express';
import { FlightService } from '../../service';
import type { FlightData } from '../../types/DataTypes';

const router = express.Router();

// 获取所有航班
router.get('/', async (req, res) => {
    try {
        const flights = await FlightService.getAllFlights();
        res.json({
            success: true,
            data: flights,
            count: flights.length
        });
    } catch (error) {
        console.error('获取航班列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取航班列表失败'
        });
    }
});

// 根据关键字搜索航班（航班号、出发城市、到达城市）
/*router.get('/search', async (req, res) => {
    try {
        const { keyword } = req.query;

        if (!keyword || typeof keyword !== 'string') {
            return res.status(400).json({
                success: false,
                message: '请输入搜索关键字'
            });
        }

        const flights = await FlightService.searchFlights(keyword);
        res.json({
            success: true,
            data: flights,
            count: flights.length
        });
    } catch (error) {
        console.error('搜索航班失败:', error);
        res.status(500).json({
            success: false,
            message: '搜索航班失败'
        });
    }
});*/

// 根据航班号搜索
/*router.get('/search/flightNum', async (req, res) => {
    try {
        const { flightNum } = req.query;

        if (!flightNum || typeof flightNum !== 'string') {
            return res.status(400).json({
                success: false,
                message: '请输入航班号'
            });
        }

        const flights = await FlightService.searchFlightsByFlightNum(flightNum);
        res.json({
            success: true,
            data: flights,
            count: flights.length
        });
    } catch (error) {
        console.error('按航班号搜索失败:', error);
        res.status(500).json({
            success: false,
            message: '按航班号搜索失败'
        });
    }
});*/

// 根据出发城市搜索
/*router.get('/search/fromCity', async (req, res) => {
    try {
        const { city } = req.query;

        if (!city || typeof city !== 'string') {
            return res.status(400).json({
                success: false,
                message: '请输入出发城市'
            });
        }

        const flights = await FlightService.searchFlightsByFromCity(city);
        res.json({
            success: true,
            data: flights,
            count: flights.length
        });
    } catch (error) {
        console.error('按出发城市搜索失败:', error);
        res.status(500).json({
            success: false,
            message: '按出发城市搜索失败'
        });
    }
});*/

// 根据到达城市搜索
/*router.get('/search/arivCity', async (req, res) => {
    try {
        const { city } = req.query;

        if (!city || typeof city !== 'string') {
            return res.status(400).json({
                success: false,
                message: '请输入到达城市'
            });
        }

        const flights = await FlightService.searchFlightsByArivCity(city);
        res.json({
            success: true,
            data: flights,
            count: flights.length
        });
    } catch (error) {
        console.error('按到达城市搜索失败:', error);
        res.status(500).json({
            success: false,
            message: '按到达城市搜索失败'
        });
    }
});*/

// 高级搜索航班（支持多条件组合）
router.get('/search/advanced', async (req, res) => {
    try {
        const {
            flightNum,
            fromCity,
            arivCity,
        } = req.query;

        // 至少需要一个搜索条件
        if (!flightNum && !fromCity && !arivCity) {
            return res.status(400).json({
                success: false,
                message: '请至少提供一个搜索条件（航班号、出发城市或到达城市）'
            });
        }

        const flights = await FlightService.advancedSearch({
            flightNum: flightNum as string,
            fromCity: fromCity as string,
            arivCity: arivCity as string
        });

        res.json({
            success: true,
            data: flights,
            count: flights.length
        });
    } catch (error) {
        console.error('高级搜索航班失败:', error);
        res.status(500).json({
            success: false,
            message: '高级搜索航班失败'
        });
    }
});

// 添加新航班
router.post('/', async (req, res) => {
    try {
        const { flightNum, fromCity, arivCity, price, totalSeat, availSeat }: FlightData = req.body;

        // 验证必填字段
        if (!flightNum || !fromCity || !arivCity || price < 0 || totalSeat <= 0) {
            return res.status(400).json({
                success: false,
                message: '输入参数错误'
            });
        }

        const flightData: FlightData = {
            flightNum,
            fromCity,
            arivCity,
            price: Number(price),
            totalSeat: Number(totalSeat),
            availSeat: availSeat !== undefined ? Number(availSeat) : Number(totalSeat)
        };

        const success = await FlightService.addFlight(flightData);

        if (success) {
            res.status(201).json({
                success: true,
                message: '航班添加成功',
                data: flightData
            });
        } else {
            res.status(500).json({
                success: false,
                message: '航班添加失败'
            });
        }
    } catch (error: any) {
        console.error('添加航班失败:', error);

        if (error.message.includes('已存在')) {
            res.status(409).json({
                success: false,
                message: error.message
            });
        } else {
            res.status(500).json({
                success: false,
                message: '添加航班失败'
            });
        }
    }
});

// 更新航班信息
router.put('/update', async (req, res) => {
    try {
        const flightData: FlightData = req.body;

        // 验证必填字段
        if (!flightData.flightNum) {
            return res.status(400).json({
                success: false,
                message: '航班号不能为空'
            });
        }

        const success = await FlightService.updateFlight(flightData);

        if (success) {
            res.json({
                success: true,
                message: '航班信息更新成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '航班不存在或更新失败'
            });
        }
    } catch (error) {
        console.error('更新航班信息失败:', error);
        res.status(500).json({
            success: false,
            message: '更新航班信息失败'
        });
    }
});

// 航班可用座位数量+1
router.patch('/:flightNum/increment', async (req, res) => {
    try {
        const { flightNum } = req.params;

        const success = await FlightService.incrementFlightAvailability(flightNum);

        if (success) {
            res.json({
                success: true,
                message: '航班可用座位+1成功'
            });
        } else {
            res.status(400).json({
                success: false,
                message: '航班不存在或可用座位已达上限'
            });
        }
    } catch (error) {
        console.error('增加航班可用座位失败:', error);
        res.status(500).json({
            success: false,
            message: '增加航班可用座位失败'
        });
    }
});

// 航班可用座位数量-1
router.patch('/:flightNum/decrement', async (req, res) => {
    try {
        const { flightNum } = req.params;

        const success = await FlightService.decrementFlightAvailability(flightNum);

        if (success) {
            res.json({
                success: true,
                message: '航班可用座位-1成功'
            });
        } else {
            res.status(400).json({
                success: false,
                message: '航班不存在或可用座位已为0'
            });
        }
    } catch (error) {
        console.error('减少航班可用座位失败:', error);
        res.status(500).json({
            success: false,
            message: '减少航班可用座位失败'
        });
    }
});

// 删除航班
router.delete('/:flightNum', async (req, res) => {
    try {
        const { flightNum } = req.params;

        const success = await FlightService.deleteFlight(flightNum);

        if (success) {
            res.json({
                success: true,
                message: '航班删除成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '航班不存在或删除失败'
            });
        }
    } catch (error) {
        console.error('删除航班失败:', error);
        res.status(500).json({
            success: false,
            message: '删除航班失败'
        });
    }
});

export default router;